package br.edu.infnet.avaliacao.interceptor;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.edu.infnet.avaliacao.controller.IndexController;
import br.edu.infnet.avaliacao.dao.DAO;
import br.edu.infnet.avaliacao.model.Usuario;
import br.edu.infnet.avaliacao.sessao.UsuarioWeb;

@Intercepts
public class AutenticacaoInterceptor implements Interceptor {

	private HttpServletRequest request;
	private EntityManager entityManager;
	private UsuarioWeb usuarioWeb;

	public AutenticacaoInterceptor(HttpServletRequest request , Result result , EntityManager entityManager , UsuarioWeb usuarioWeb) {
		this.request = request;
		this.entityManager = entityManager;
		this.usuarioWeb = usuarioWeb;
	}

	@Override
	public boolean accepts(ResourceMethod method) {
		if(request.getRemoteUser() != null){
			if(!usuarioWeb.isLogado()){
				DAO<Usuario> dao = new DAO<Usuario>(Usuario.class, entityManager);
				usuarioWeb.login(dao.getObject("username", request.getRemoteUser()));
			}
		}else{
			usuarioWeb.logout();
		}
		return false;
	}

	@Override
	public void intercept(InterceptorStack arg0, ResourceMethod arg1, Object arg2) throws InterceptionException {
		
	}

}
